package com.netty.demo.server.netty.listener;

import com.netty.demo.server.netty.config.NettyConfig;
import com.netty.demo.server.netty.model.NettyNetwork;
import com.netty.demo.server.utils.StringUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.util.List;

/**
 * 转发消息工具类
 *
 * @author Administrator 余秀良
 * @version 1.0
 * <p>date: 2019年09月23日  15:24 </p>
 * <p>address: 四川成都 </p>
 */
@Slf4j
@Component
public class ForwardMessageListener {
    /**
     * 转发消息
     *
     * @param message ForwardMessage
     * @author 余秀良
     * @version 1.0
     * <p>  date: 2019 - 09 - 23  15:25    </p>
     * <p>  address: 四川成都  </p>
     */
    @Async
    @EventListener
    public void sendMessage(ForwardMessage message) {
        DatagramPacket packet = message.getPacket();
        int port = packet.recipient().getPort();
        List<NettyNetwork> nettyNetworkList = NettyConfig.getServerConfig();
        nettyNetworkList.forEach(nettyNetwork -> {
            String monitorPort = nettyNetwork.getMonitorPort();
            if (StringUtil.isNotEmpty(monitorPort) && Integer.parseInt(monitorPort) == port) {
                if (StringUtil.isNotEmpty(nettyNetwork.getIsForward()) && Boolean.parseBoolean(nettyNetwork.getIsForward())) {
                    String forwardIp = nettyNetwork.getForwardIp();
                    String forwardPort = nettyNetwork.getForwardPort();
                    if (StringUtil.isNotEmpty(forwardIp) && StringUtil.isNotEmpty(forwardPort)) {
                        log.info("开始转发消息 ip {} 端口 {}", forwardIp, forwardPort);
                        InetSocketAddress inetSocketAddress = new InetSocketAddress(forwardIp, Integer.parseInt(forwardPort));
                        DatagramPacket datagramPacket = new DatagramPacket(packet.content(), inetSocketAddress);
                        message.getCtx().channel().writeAndFlush(datagramPacket);
                    }
                }
            }
        });
    }

    @Getter
    @Setter
    @Accessors(chain = true)
    @AllArgsConstructor
    @NoArgsConstructor
    public static class ForwardMessage {
        private ChannelHandlerContext ctx;
        private DatagramPacket packet;
    }
}
